<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter @filterchange="filterchange" />
      <!-- 商品面板：排序+列表 -->
      <div class="goods-list">
        <SubSort @sortchange="sortchange"></SubSort>
        <!-- 列表 -->
        <ul>
          <li v-for="item in goodslist"
              :key="item.id">
            <GoodsItem :good="item" />
          </li>
        </ul>
        <!-- 无限加载组件 -->
        <XtxInfiniteLoading :loading="loading"
                            :finished="finished"
                            @infinite="getData"></XtxInfiniteLoading>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryGoods } from '@/apis/category'
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from './components/goods-item.vue'
export default {
  name: 'Sub',
  components: { SubBread, SubFilter, SubSort, GoodsItem },
  setup () {
    const route = useRoute()
    // 是否加载中
    const loading = ref(false)
    // 是否加载完成
    const finished = ref(false)
    // 商品列表数据
    const goodslist = ref([])
    // 请求参数
    let requestparams = {
      page: 1,
      pageSize: 20
    }
    // 获取数据
    const getData = () => {
      loading.value = true
      requestparams.categoryId = route.params.id
      findSubCategoryGoods(requestparams).then(({ result }) => {
        if (result.items.length) {
          goodslist.value.push(...result.items)
        } else {
          finished.value = true
        }
        loading.value = false
        requestparams.page++
      })
    }

    // 当地址栏改变时，清空数据
    watch(
      () => route.params.id,
      (newid) => {
        if (newid && `/category/sub/${newid}` === route.path) {
          requestparams = {
            page: 1,
            pageSize: 20
          }
          finished.value = false
          goodslist.value = []
        }
      }
    )
    const checked = ref(true)

    // 排序改变，重新请求数据
    const sortchange = (sortparams) => {
      finished.value = false
      requestparams = { ...requestparams, ...sortparams }
      requestparams.page = 1
      goodslist.value = []
    }
    // 过滤数据改变
    const filterchange = (filterparams) => {
      finished.value = false
      requestparams = { ...requestparams, ...filterparams }
      requestparams.page = 1
      goodslist.value = []
    }
    return {
      checked,
      loading,
      finished,
      getData,
      goodslist,
      sortchange,
      filterchange
    }
  }
}
</script>

<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
